import React, { Component } from 'react'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { Button, Drawer, Alert, Badge, Divider, Modal, Select, Form } from 'antd'
import { Link } from 'react-router-dom'
import * as StayGrantService from '../../../axios/StayGrant'
import * as APIService from '../../../axios/api';
import TopForm from './TopForm'
import PickingTable from './PickingTable'
import img from '../../../assets/img/flame.png'
import SubmitOwe from './SubmitOwe'
import { withRouter } from 'react-router';
import { withPermission } from '../../../components/withpermission'
const RefreshButton = withPermission(Button, 'sync')
const QRButton = withPermission(Button, 'queren')
const FFButton = withPermission(Button, 'fafang')
const { Option } = Select

const printRows = 40
class StayGrant extends Component {
    state = {
        pages: [],
        printRows: printRows,
        columns: [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                width: 60,
                render: (text, record, index) => <div style={{ display: 'flex' }}>
                    <div>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</div>
                    {record.isRush === 1 || record.isRush === '1' ? <img src={img} style={{ width: '18px', height: '18px' }} /> : null}
                </div>,
            },
            {
                title: '领料单号',
                dataIndex: 'acceptCode',
                sorter: (a, b) => compareString(a.acceptCode, b.acceptCode),
                width: 150,
            },
            {
                title: '批号',
                dataIndex: 'batchNo',
                sorter: (a, b) => compareString(a.batchNo, b.batchNo),
                width: 100,
            },
            {
                title: '机型',
                dataIndex: 'model',
                sorter: (a, b) => compareString(a.model, b.model),
                width: 180,

            },
            {
                title: '装配部门',
                dataIndex: 'departName',
                sorter: (a, b) => compareString(a.departName, b.departName),
                width: 110,

            },
            {
                title: '领料班组',
                dataIndex: 'groupName',
                sorter: (a, b) => compareString(a.groupName, b.groupName),
                width: 100,

            },
            {
                title: '班组长',
                dataIndex: 'groupLeader',
                sorter: (a, b) => compareString(a.groupLeader, b.groupLeader),
                width: 80,

            },
            {
                title: '领料项',
                dataIndex: 'acceptItem',
                sorter: (a, b) => compareString(a.acceptItem, b.acceptItem),
                width: 80,

            },
            {
                title: '申请时间',
                dataIndex: 'createTime',
                sorter: (a, b) => compareString(a.createTime, b.createTime),
                width: 150,

            },
            {
                title: '装配开始时间',
                dataIndex: 'assembleStartTime',
                sorter: (a, b) => compareDate(a.assembleStartTime, b.assembleStartTime),
                width: 150,

            },
            {
                title: '需求时间',
                dataIndex: 'requestTime',
                sorter: (a, b) => compareDate(a.requestTime, b.requestTime),
                width: 150,

            },
            {
                title: '操作',
                dataIndex: 'opes',
                width: 200,
                render: (text, record, index) =>
                    <div>
                        <a onClick={this.print.bind(null, record)}>{'打印'}</a>
                        <Divider type="vertical" />
                        <a onClick={this.particulars.bind(null, record)}>{'详情'}</a>
                        <Divider type="vertical" />
                        <a onClick={this.carryOwe.bind(null, record)}>{'提欠料'}</a>
                    </div>
            },
            { dataIndex: '' }
        ],
        dataSource: [],
        columnsInterior: [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                render: (text, record, index) => <div style={{ display: 'flex' }}>
                    <div>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</div>
                    {record.isRush === 1 || record.isRush === '1' ? <img src={img} style={{ width: '18px', height: '18px' }} /> : null}
                </div>,
                width: 60,
            },
            {
                title: '物料编码',
                dataIndex: 'partCode',
                sorter: (a, b) => compareNum(a.partCode, b.partCode),
                render: (text, record, index) =>
                    <div>
                        {
                            record.partChangeAttitude === 1 ? <Badge status="success" text={'新增'} /> : record.partChangeAttitude === 2 ? <Badge status="default" text={'取消'} /> : record.partChangeAttitude === 3 ? <Badge status="warning" text={'属性变化'} /> : record.partChangeAttitude === 4 ? <Badge status="processing" text={'回仓'} /> : null
                        }
                        <div>
                            {text}
                        </div>
                    </div>,
                width: 100,
            },
            {
                title: '图号',
                dataIndex: 'paperCode',
                key: 'paperCode',
                sorter: (a, b) => compareNum(a.paperCode, b.paperCode),
                width: 150,
            },
            {
                title: '仓库',
                dataIndex: 'storeName',
                width: 100
            },
            {
                title: '装配组别',
                dataIndex: 'assemblyGroup',
                key: 'assemblyGroup',
                width: 130,
            },
            {
                title: '物料名称',
                dataIndex: 'partName',
                key: 'partName',
                width: 100,
            },
            {
                title: '物料规格',
                dataIndex: 'partSpec',
                key: 'partSpec',
                width: 100,
            },
            {
                title: '领料数量',
                dataIndex: 'acceptNum',
                key: 'acceptNum',
                sorter: (a, b) => compareNum(a.acceptNum, b.acceptNum),
                width: 100,
            },
            {
                title: '发料状态',
                dataIndex: 'outStatus',
                key: 'outStatus',
                sorter: (a, b) => compareString(a.outStatus, b.outStatus),
                width: 100,
                render: (text, record, index) =>
                    <div>
                        {
                            record.isLack === 1 ? <Badge status="error" text={<span style={{ color: 'red' }}>欠料</span>} /> : null
                        }
                        <div>
                            {
                                text === 1 ? <Badge status="error" text={<span style={{ color: 'red' }}>待确认</span>} /> : null
                            }
                        </div>
                        <div>
                            {
                                text === 2 ? <Badge status="processing" text='未完成' /> : text === 3 ? <Badge status="success" text="已完成" /> : null
                            }
                        </div>
                    </div>
            },
            { dataIndex: '' }
        ],
        dataSourceInterior: [],
        advanced: false,
        formData: {},
        drawerVisible: false,
        drawerVisible1: false,
        visible: false,
        showConceal: false,
        loginFlag: false,
        selectedRows: [],
        selectedRowKeys: [],
        selectedRowKeys1: [],
        selectedRows1: [],
        row: [],
        row1: [],
        pageNum: 1,
        pageSize: 100,
        total: 0,
        searchItem: {},
        workShopList: [],
        materialData: [],
        acceptMap: [],
        loadingDrawer: false,
        ERPReturn: null,
        submit: {},
        submits: {},
        submitOweMaterial: false,
        buttons: [],
        takeNumber: [],
        options: [],
        warehouse: [],
        pitchOnAffirm: [],
        fatherId: null,
        fatherData: null,

    }
    componentDidMount() {
        const { searchItem } = this.state
        searchItem.storeName = localStorage.getItem('department')
        this.setState({
            searchItem
        }, () => {
            let acceptPublishListSubmit = localStorage.getItem("acceptPublishListSubmit");
            StayGrantService.maxAcceptCode(acceptPublishListSubmit ? acceptPublishListSubmit : null).then((value) => {
                localStorage.setItem("acceptPublishListSubmit", value.data.msg);
                this.fetch();
                this.getWorkShopList();
            })
        })
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    getWorkShopList = () => {
        const then = this
        // StayGrantService.workShopList().then(res => {
        //     if (res.data.code !== 200) {
        //         openModalMessage('warning', res.data.msg);
        //         return;
        //     }
        //     const workShopList = res.data && res.data.data ? res.data.data : []
        //     this.setState({ workShopList })
        // }).catch(err => {
        //     openModalMessage('error', err.message);
        // })
        //查询所有部门组装成级联选择框
        APIService.getDepartMents().then(data => {
            // console.log('部门数据', data.data.data);
            const dataSource = data.data.data;
            const options = [];
            for (var value of dataSource) {
                var json = { "label": value.name, "value": value.id, 'children': [] }
                console.log('zhes', value);
                if (value.name == '仓库') {
                    this.setState({
                        warehouse: value.children
                    })
                }
                if (value.children.length !== 0) {
                    for (var valueFirst of value.children) {
                        var json2 = { "label": valueFirst.name, "value": valueFirst.id, 'children': [] }
                        json.children.push(json2)
                    }
                }
                options.push(json);
            }
            // console.log('部门最终数据', options);
            this.setState({
                options: options
            })
        }
        )

        StayGrantService.dynamicQueryButton().then((res) => {
            // console.log('查询按钮', res);
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            if (res.data.data[0] === undefined) {
                this.setState({ searchItem: {} }, () => { this.fetch() });
            }
            const { buttons, dataSource, searchItem } = this.state;
            const dynamicQueryButton = res.data && res.data.data[0] !== undefined ? res.data.data : []
            const button = [
                <RefreshButton key={1} onClick={() => this.update()} icon='sync' />,
                <QRButton key={2} onClick={() => this.affirm()} />,
                <FFButton key={3} onClick={() => this.grant()} />,

                // <Button key={1} onClick={this.update} type="primary" icon='sync'>刷新</Button>,
                // <Button key={2} onClick={this.affirm} type="primary" >领取单确认</Button>,
                // <Button key={3} onClick={this.grant} type="primary" >物料发放</Button>,
            ]
            dynamicQueryButton.forEach((value, index) => {
                const div = value && value.departmentId ? <Badge count={value.undoCount} key={`${value.departmentId}_new`}> <Button type='default' onClick={() => this.setLocationCode(value)}>{value.departmentName}</Button></Badge> : null
                //   更新徽章数
                if (searchItem.departmentId === value.departmentId) {
                    button[index + 3] = <Badge count={value.undoCount} key={`${value.departmentId}_new`}> <Button type='default' onClick={() => this.setLocationCode(value)}>{value.departmentName}</Button></Badge>
                } else {
                    button.push(div)
                }
                // this.fetch()
            })
            this.setState({ buttons: button })
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true });
        const { searchItem } = this.state;
        searchItem.pageNum = pageNum;
        searchItem.pageSize = pageSize;
        StayGrantService.waitingForSendList(searchItem).then(res => {
            this.setState({ loading: false })
            // console.log(res);
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            this.setState({ dataSource: res.data.data, total: res.data.total, pageNum, pageSize, selectedRowKeys: [], selectedRows: [], selectedRowKeys1: [], selectedRows1: [], dataSourceInterior: [], fatherId: null, fatherData: null });
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    setLocationCode = (item) => {
        // console.log(item);
        const { searchItem } = this.state;
        searchItem.departmentId = item.departmentId;
        searchItem.isSure = 0
        this.setState({ searchItem }, () => {
            this.fetch()
        })
    }
    // 高级查询
    advancedss = () => {
        // console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    // 领取单确认
    affirm = () => {
        const that = this;
        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            // console.log(acceptPublishListSubmit, value.data.msg);
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }
            const { selectedRows, selectedRows1, pitchOnAffirm } = this.state
            // console.log('子级选择', selectedRows1);
            if ((!selectedRows || !selectedRows.length) && (!selectedRows1 || !selectedRows1.length)) {
                openModalMessage('warning', '请选择数据');
                return;
            }
            let arr = '';
            for (var item of pitchOnAffirm) {
                arr += `&idList=${item}`;
            }
            if (arr.length == 0) {
                openModalMessage('warning', '没有合适的确认项');
                return
            }
            let affirm = `userId=${localStorage.getItem('userId')}${arr}`;
            let obj = { idList: pitchOnAffirm }
            StayGrantService.confirmAcceptCode(obj).then((value) => {
                if (value.data.code !== 200) {
                    openModalMessage('warning', value.data.msg);
                    return;
                }
                this.handleCancel()
                this.getWorkShopList()
                that.fetch()
            }).catch(err => {
                openModalMessage('error', err.message);
                return
            })
        })
    }

    // 物料发放（批量）
    grant = () => {
        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        // console.log(acceptPublishListSubmit);
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            // console.log(value);
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }
            // const { selectedRows } = this.state
            // if (!selectedRows || !selectedRows.length) {
            //     openModalMessage('warning', '请选择数据');
            //     return;
            // }
            // const that = this;
            // let selectedRows1 = selectedRows
            // let arr = '';
            // for (var item of selectedRows1) {
            //     arr += `&idList=${item.id}`;
            // }
            // StayGrantService.grantAcceptCode(arr).then((value) => {


            const { selectedRows, selectedRows1, selectedRowKeys, selectedRowKeys1, pitchOnAffirm } = this.state
            console.log('选择', selectedRows, selectedRows1, selectedRowKeys, selectedRowKeys1, pitchOnAffirm);
            if ((!selectedRows || !selectedRows.length) && (!selectedRows1 || !selectedRows1.length)) {
                openModalMessage('warning', '请选择数据');
                return;
            }
            let obj = { idList: pitchOnAffirm }
            StayGrantService.grantAcceptCodeDetail(obj).then((value) => {
                if (value.data.code !== 200) {
                    openModalMessage('warning', value.data.msg);
                    return;
                }
                this.setState({
                    materialData: value.data.data,
                    drawerVisible: true
                })
            }).catch(err => {
                openModalMessage('error', err.message);
                return
            })
        })
    }
    handleSearch = value => {
        value.departmentId = value.departmentId === undefined ? null : value.departmentId[value.departmentId.length - 1];
        this.setState({ searchItem: value }, () => {
            this.fetch();
            this.onExpand(false)
        }
        );
    };
    loadData = (value, dataSource) => {
        console.log('在表格行编辑后保存的数据', value, dataSource)
    }
    // 发放
    onHandleOk = () => {
        let takeNum = this.state.takeNumber
        takeNum.sort((a, b) => {
            return a - b
        })
        if (takeNum[0] === 0) {
            openModalMessage('warning', '有已发放完毕数据,请重新选择');
            return
        }
        const { acceptMap, nowDates } = this.state;
        let arr = '';
        for (var item of acceptMap) {
            for (const iterator of item.bodyVOList) {
                arr += `&idList=${iterator.id}`;
            }
        }
        if (!Object.keys(acceptMap).length) {
            openModalMessage('warning', '请重新选择要发布的数据！');
            this.handleCancel();
            return;
        }
        // 改变对象key
        let datas = []
        acceptMap.map((value, index) => {
            let obj = {}
            for (const key in value) {
                let a = key
                if (a === 'bodyVOList') {
                    a = 'bodyAddDTOList'
                }
                obj[a] = value[key]
            }
            datas.push({ ...obj, userId: Number(localStorage.getItem('userId')) })
        })
        // console.log('改变前', acceptMap);
        // console.log('改变后', datas);
        this.setState({ loadingDrawer: true });
        StayGrantService.publishAcceptCode(datas).then(res => {
            this.setState({ loadingDrawer: false });
            // console.log(res);
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            StayGrantService.publishMaterialResult(arr).then((value) => {
                if (value.data.code !== 200) {
                    openModalMessage('warning', value.data.msg);
                    return;
                }
                this.setState({
                    showConceal: true,
                    ERPReturn: value.data.data,
                })
            })
        }).catch(err => {
            openModalMessage('error', err.message);
            this.setState({ loadingDrawer: false })
        })


        // this.setState({
        //     // drawerVisible: false,
        //     // showConceal: true
        // });
    }
    // 取消
    handleCancel = e => {
        this.setState({
            drawerVisible: false,
            showConceal: false,
            materialData: [],
            selectedRows: [],
            selectedRowKeys: [],
            ERPReturn: null,
            row: [],
            printRows: printRows
        }, () => {
            this.fetch()
            this.state.row.length > 0 && this.onExpand(true, { id: this.state.row[0] })
        });

    };
    // 操作-确认
    notarize = (record, e) => {
        e.stopPropagation()
        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }
            let idList = `storeName=${localStorage.getItem('department')}&idList=${record.id}`
            StayGrantService.idListDetail(idList).then(res => {
                if (res.data.code !== 200) {
                    openModalMessage('warning', value.data.msg);
                    return
                }
                let idLists = res.data.data
                let id = ''
                idLists.forEach((value, index) => {
                    id += `&idList=${value}`
                })
                if (id.length == 0) {
                    openModalMessage('warning', '没有合适的确认项');
                    return
                }
                let arr = `userId=${localStorage.getItem('userId')}${id}`;
                StayGrantService.confirmAcceptCode(arr).then((value) => {
                    // console.log('确认', value);
                    if (value.data.code === 200) {
                        this.handleCancel()
                        this.getWorkShopList();
                        this.fetch()
                        return;
                    }
                    openModalMessage('warning', value.data.msg);

                }).catch(err => {
                    openModalMessage('error', err.message);
                    return
                })
            })
        })

    }
    // 打印
    print = (record, e) => {
        console.log(e, 'print');
        e.stopPropagation()
        // openModalMessage('warning', '功能待开发')

        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        console.log(acceptPublishListSubmit);
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            // console.log(value);
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }

            StayGrantService.sendListDetail({ ...record, pageSize: 999999, storeName: this.state.searchItem.storeName }).then(res => {
                if (res.data.code != 200) {
                    openModalMessage('warning', res.data.msg)
                    return
                }
                let data = res.data.data, printRows = this.state.printRows
                let pages = []
                for (let i = 0; i < Math.ceil(data.length / printRows); i++) {
                    pages.push(i)
                }
                console.log(pages, 'pages');
                this.setState({ printData: data, pages }, () => {
                    var printInnerHTML = window.document.getElementById('prints').innerHTML;
                    window.document.body.innerHTML = printInnerHTML
                    window.print();
                    window.location.reload();
                })
            }).catch(err => {
                openModalMessage('error', err.message);
                return
            })

        })
    }
    // 详情
    particulars = (r, e) => {
        e.stopPropagation()
        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }
            sessionStorage.setItem('particulars_acceptCode', JSON.stringify(r.acceptCode))
            this.props.history.push({ pathname: "/particulars", data: { acceptCode: r.acceptCode } })
        })
    }
    // 提欠料
    carryOwe = (record, e) => {
        e.stopPropagation()
        let acceptPublishListSubmit = localStorage.getItem('acceptPublishListSubmit')
        StayGrantService.maxAcceptCode(acceptPublishListSubmit).then((value) => {
            if (acceptPublishListSubmit !== value.data.msg) {
                this.setState({
                    control: true,
                    control1: value.data.msg
                })
                openModalMessage('warning', '数据有更新，请刷新重试')
                return
            }
            // let arr = `idList=${record.id}`;
            let arr = `acceptCode=${record.acceptCode}`;
            StayGrantService.materialShortageList(arr).then((value) => {
                if (value.data.code !== 200) {
                    openModalMessage('warning', value.data.msg);
                    return;
                }
                this.setState({
                    submit: value.data.data,
                    drawerVisible1: true
                })
            }).catch(err => {
                openModalMessage('error', err.message);
                return
            })
        })
    }
    // 取消提交欠料
    handleCancel2 = () => {
        // console.log('取消');
        this.setState({
            submitOweMaterial: false,
            drawerVisible1: false,
            submit: {}
        });
    }
    //提交欠料
    submits = () => {
        // console.log('这是什么', this.state.submits, this.state.takeNumber1);
        let takeNum1 = this.state.takeNumber1
        takeNum1.sort((a, b) => {
            return a - b
        })
        if (this.state.submits[0] == undefined) {
            openModalMessage('warning', '请重新选择数据');
            this.setState({
                drawerVisible1: false,
                submitOweMaterial: false
            }, () => {
                this.fetch()
            })
            return
        }
        if (takeNum1[0] === 0) {
            openModalMessage('warning', '有已发放完毕数据,请重新选择');
            return
        }
        this.setState({
            submitOweMaterial: true
        })
        const { submits } = this.state
        let disposeData = []
        submits.forEach((value, index) => {
            let obj = {}
            for (const key in value) {
                let a = key
                if (a === 'bodyVOList') {
                    a = 'bodyAddDTOList'
                }
                obj[a] = value[key]
            }
            disposeData.push({ ...obj, userId: Number(localStorage.getItem('userId')) })
        })
        StayGrantService.materialShortageSubmit(disposeData).then((value) => {
            console.log(value);
            if (value.data.code !== 200) {
                openModalMessage('warning', value.data.msg);
                this.setState({
                    submitOweMaterial: false
                })
                return;
            }
            openSuccessModal(value.data.msg)
            this.setState({
                drawerVisible1: false,
                submitOweMaterial: false
            });

        })

    }

    // 物料发放结果打印
    resultPrint = () => {
        // console.log('物料发放结果打印');
        this.setState({
            visible: true
        })
    }
    // 打印弹窗确认
    handleOk = () => {
        this.setState({
            visible: false
        })
    }
    // 打印弹窗取消
    handleCancels = () => {
        this.setState({
            visible: false
        })
    }

    // 全部提交欠料
    submitOwe = () => {
        const { ERPReturn } = this.state
        let id = []
        let arr = ''
        ERPReturn.forEach((value, index) => {
            value.bodyVOList.forEach((value_1, index_1) => {
                if (value_1.result === 0) {
                    id.push(value_1.id)
                    arr += `&idList=${value_1.id}`;
                }
            })
        })
        console.log(id[0]);
        if (id[0] === undefined) {
            openModalMessage('warning', '已经全部发放成功！！');
            return
        }
        StayGrantService.materialShortageList(arr).then((value) => {
            if (value.data.code !== 200) {
                openModalMessage('warning', value.data.msg);
                return;
            }
            this.setState({
                drawerVisible1: true,
                submit: value.data.data
            })
        })
    }


    // 展开方法
    onExpand = (expanded, record) => {
        record && this.setState({
            fatherId: record.id,
            fatherData: record
        })
        if (expanded) {
            StayGrantService.sendListDetail({ ...record, pageSize: 999999, storeName: this.state.searchItem.storeName }).then(res => {
                // console.log('展开', res);
                this.setState({
                    dataSourceInterior: res && res.data ? res.data.data : [],
                    row: [record.id],
                    // expandedData: record
                })
            })
        } else {
            this.setState({
                row: []
            })
        }
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({ searchItem: { storeName: localStorage.getItem('department') } }, () => { this.fetch(); this.onExpand(false) });
    }
    // 刷新
    update = () => {
        const { control, control1 } = this.state
        if (control) {
            localStorage.setItem('acceptPublishListSubmit', control1)
            this.setState({
                control: false
            })
        }
        this.fetch()
        this.onExpand(false)
    }
    render() {
        const { printRows, columnsInterior, dataSourceInterior, submitOweMaterial, ERPReturn, loadingDrawer, materialData, selectedRowKeys, showConceal, drawerVisible, drawerVisible1, visible, columns, loading, dataSource, advanced, selectedRowKeys1, formData, pageNum, pageSize, total, workShopList, selectedRows, buttons } = this.state;
        const batchNoStr1 = []
        selectedRows.forEach((value) => { batchNoStr1.push(value.batchNo) })
        const batchNoStr11 = Array.from(new Set(batchNoStr1))
        const batchNoStr = batchNoStr11.map(item => item).join(',')
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows
                })
                // 拿取数据
                let arr = '';
                for (var item of selectedRows) {
                    arr += `&idList=${item.id}`;
                }
                let idList = `storeName=${localStorage.getItem('department')}${arr}`
                if (selectedRows.length !== 0) {
                    StayGrantService.idListDetail(idList).then(res => {
                        if (res.data.code !== 200) return
                        this.setState({
                            pitchOnAffirm: res.data.data,
                            selectedRowKeys1: res.data.data,
                        }, () => {
                            console.log(this.state.selectedRowKeys1, 'selectedRowKeys1   -     222222222')
                        })
                    })
                    return
                }
                this.setState({
                    pitchOnAffirm: [],
                    selectedRowKeys1: []
                }, () => {
                    console.log(this.state.selectedRowKeys1, 'selectedRowKeys1   -     1111111111')
                })
            },
        }
        const expandedRowRender = () => {
            const rowSelection = {
                type: 'checkbox',
                selectedRowKeys: selectedRowKeys1,
                onChange: (selectedRowKeys1, selectedRows1) => {
                    this.setState({
                        selectedRowKeys1: selectedRowKeys1,
                        selectedRows1: selectedRows1
                    })
                },
                // 子级选择行
                onSelect: (record, selected, selectedRows) => {
                    const { pitchOnAffirm, fatherId, fatherData } = this.state
                    let selectedRowsFather = this.state.selectedRows
                    if (selected) {
                        if (selectedRows.length == dataSourceInterior.length) {
                            if (selectedRowKeys.indexOf(fatherId) == -1) {
                                selectedRowKeys.push(fatherId)
                                selectedRowsFather.push(fatherData)
                                this.setState({
                                    selectedRowKeys, selectedRows: selectedRowsFather
                                })
                            }
                        }
                        if (pitchOnAffirm.indexOf(record.id) === -1) {
                            pitchOnAffirm.push(record.id)
                        }
                        this.setState({
                            pitchOnAffirm
                        })
                        return
                    }
                    selectedRowKeys.splice(selectedRowKeys.indexOf(fatherId), 1)
                    selectedRowsFather.splice(selectedRowsFather.indexOf(fatherData), 1)
                    pitchOnAffirm.splice(pitchOnAffirm.indexOf(record.id), 1)
                    this.setState({
                        pitchOnAffirm,
                        selectedRowKeys,
                        selectedRows: selectedRowsFather
                    })
                },
                // 子级全选
                onSelectAll: (selected, selectedRows, changeRows) => {
                    const { pitchOnAffirm, fatherId, fatherData } = this.state
                    let selectedRowsFather = this.state.selectedRows
                    if (selected) {
                        if (selectedRowKeys.indexOf(fatherId) == -1) {
                            selectedRowKeys.push(fatherId)
                            selectedRowsFather.push(fatherData)
                            this.setState({
                                selectedRowKeys, selectedRows: selectedRowsFather
                            })
                        }
                        selectedRows.forEach((value, index) => {
                            if (pitchOnAffirm.indexOf(value.id) === -1) {
                                pitchOnAffirm.push(value.id)
                            }
                        })
                        this.setState({
                            pitchOnAffirm
                        })

                        return
                    }
                    selectedRowKeys.splice(selectedRowKeys.indexOf(fatherId), 1)
                    selectedRowsFather.splice(selectedRowsFather.indexOf(fatherData), 1)
                    changeRows.forEach((value, index) => {
                        pitchOnAffirm.splice(pitchOnAffirm.indexOf(value.id), 1)
                    })
                    this.setState({
                        pitchOnAffirm,
                        selectedRowKeys,
                        selectedRows: selectedRowsFather
                    })
                }
            }
            return <TableCustomize
                rowSelection={rowSelection}
                columns={columnsInterior}
                rowKey={(record) => record.id}
                dataSource={dataSourceInterior}
                pagination={false}
                allowDrafting={true}
                allowEditable={this.loadData}
                // onRow={(record, index) => ({
                //     onClick: this.pitch1.bind(this, record, index)
                // })}
                rowClassName={(record, index) => {
                    return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                }}
                scroll={{ y: 300 }}
            />;
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <TopForm onSearch={this.handleSearch}
                        onClick4={this.advancedss}
                        advanced={advanced}
                        options={this.state.options}
                        warehouse={this.state.warehouse}
                        resetForm={this.resetForm}
                        ref={node => (this.formSearch = node)}
                    ></TopForm>
                </BasicLayoutSearch>
                <Alert
                    message={<div>已选择<span style={{ color: '#1890ff', margin: '0 3px' }}>{selectedRowKeys.length}</span>项，包括<span style={{ color: '#1890ff', margin: '0 3px' }}>{batchNoStr11.length}</span>个批号{batchNoStr}</div>}
                    type="info"
                    showIcon
                    style={{ width: '99%', margin: 'auto' }}
                    action={
                        <a onClick={() => this.setState({ selectedRowKeys: [], selectedRows: [] })}>
                            清除
                        </a>
                    } />
                <BasicLayout
                    name={`待发放物料-${localStorage.getItem('department')}`}
                    icon="table"
                    buttons={buttons}
                >
                    <TableCustomize
                        rowSelection={rowSelection}
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        allowEditable={this.loadData}
                        expandedRowRender={expandedRowRender}
                        // onRow={(record, index) => ({
                        //     onClick: this.onExpand.bind(this, true, record)
                        // })}
                        expandRowByClick={true}
                        onExpand={(expanded, record) => this.onExpand(expanded, record)}
                        expandedRowKeys={this.state.row}
                        scroll={{ x: true, y: 600 }}
                        rowClassName={(record, index) => {
                            return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                        }}
                    />
                    <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                </BasicLayout>
                <Drawer width={1300} visible={drawerVisible} title={'物料发放确认'} onClose={this.handleCancel} maskClosable={false} destroyOnClose={true} style={{ zIndex: '2' }}>
                    <PickingTable
                        onOk={this.onHandleOk}
                        onClose={this.handleCancel}
                        materialData={materialData}
                        showConceal={showConceal}
                        ERPReturn={ERPReturn}
                        saveAcceptMap={(value) => this.setState({ acceptMap: value }, console.log('回调数据', value))}
                        submit={(v) => {
                            let arr = '';
                            v.forEach((value, index) => {
                                arr += `&idList=${value}`
                            })
                            StayGrantService.materialShortageList(arr).then((value) => {
                                if (value.data.code !== 200) {
                                    openModalMessage('warning', value.data.msg);
                                    return;
                                }
                                this.setState({
                                    drawerVisible1: true,
                                    submit: value.data.data
                                })
                            })


                        }}
                        takeNumber={(v) => this.setState({
                            takeNumber: v
                        })}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: '10px' }}>{'取消'}</Button>
                        {
                            showConceal ? <Button style={{ marginRight: '10px' }} type="primary" onClick={this.submitOwe}>全部提交欠料</Button> : <Button type="primary" onClick={this.onHandleOk} loading={loadingDrawer}>
                                {'发放'}
                            </Button>
                        }
                        {
                            showConceal ? <Button type="primary" onClick={this.resultPrint}>打印</Button> : null
                        }
                    </div>
                </Drawer>

                <Drawer width={1300} visible={drawerVisible1} title={'提交欠料'} onClose={this.handleCancel2} destroyOnClose={true} maskClosable={false} >
                    <SubmitOwe
                        onOk={this.submits}
                        onClose={this.handleCancel2}
                        selectedRows={this.state.selectedRows}
                        submit={this.state.submit}
                        showConceal={showConceal}
                        submits={(v) => this.setState({ submits: v }, () => { console.log('回调数据', v); })}
                        takeNumber1={(v) => this.setState({
                            takeNumber1: v
                        })}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel2} style={{ marginRight: '10px' }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.submits} loading={submitOweMaterial}>{'提交欠料'}</Button>
                    </div>
                </Drawer>

                {/* <Modal
                    title="请选择需要打印的领料单批次"
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancels}
                    okText="确认"
                    cancelText="取消"
                >
                    批次: <Select defaultValue={'PJ02'}>
                        <Option value='PJ01' key={'PJ01'}>PJ01</Option>
                        <Option value='PJ02' key={'PJ02'}>PJ02</Option>
                        <Option value='PJ03' key={'PJ03'}>PJ03</Option>
                        <Option value='PJ04' key={'PJ04'}>PJ04</Option>
                    </Select>
                </Modal> */}


                {/* 打印 20221025 */}
                <div id="prints" style={{ display: 'none' }}>
                    {
                        this.state.pages.map((pa, i) => {
                            return <div className='cardStyle_mini card' id={'cardStyle' + i} key={i} style={{ width: '97%', color: 'black', padding: '15px 10px 0 10px', height: 'calc(100% - 30px)', margin: 'auto', position: 'relative', fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'" }}>
                                <div style={{ width: '100%', textAlign: 'center' }}>
                                    <div style={{ width: '100%', margin: 'auto', fontSize: 20, fontWeight: 700 }}>待发放物料详情</div>
                                </div>
                                <div style={{ width: '100%', fontSize: 14 }}>
                                    <table width="100%" style={{ margin: '5px 0', fontSize: 14 }}>
                                        <thead>
                                            <tr style={{ borderTop: '1px dashed #333', borderBottom: '1px dashed #333' }}>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', width: 30, fontWeight: 'normal', padding: '5px 0', textAlign: 'center' }}>序号</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal' }}>物料编码</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal' }}>图号</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal' }}>仓库</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal' }}>装配组别</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal' }}>物料名称</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal', textAlign: 'center' }}>物料规格</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal', textAlign: 'center' }}>领料数量</th>
                                                <th style={{ padding: '5px 0', borderTop: '1px dashed #333', borderBottom: '1px dashed #333', fontWeight: 'normal', textAlign: 'center' }}>发料状态</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {this.state.printData.slice(pa * printRows, (pa + 1) * printRows).map((itt, i) => {
                                                return <>
                                                    <tr style={{ height: 15 }} key={i}>
                                                        <td style={{ textAlign: 'center' }}>{pa * printRows + i + 1}</td>
                                                        <td><span style={{ display: 'inline-block', height: 15, whiteSpace: 'nowrap' }}>{itt.partCode}</span></td>
                                                        <td><span style={{ display: 'inline-block', height: 15, width: 30, whiteSpace: 'nowrap' }}>{itt.paperCode}</span></td>
                                                        <td><span style={{ display: 'inline-block', height: 15, whiteSpace: 'nowrap' }}>{itt.storeName}</span></td>
                                                        <td><span style={{ display: 'inline-block', height: 15, lineHeight: '16px', whiteSpace: 'nowrap', overflow: 'hidden' }}>{itt.assemblyGroup}</span></td>
                                                        <td><span style={{ display: 'inline-block', height: 15, lineHeight: '16px', whiteSpace: 'nowrap', overflow: 'hidden' }}>{itt.partName}</span></td>
                                                        <td style={{ textAlign: 'center' }}><span style={{ display: 'inline-block', height: 15, lineHeight: '16px', width: 40, whiteSpace: 'nowrap' }}>{itt.partSpec}</span></td>
                                                        <td style={{ textAlign: 'center' }}><span style={{ display: 'inline-block', height: 15, lineHeight: '16px', width: 60, whiteSpace: 'nowrap' }}>{itt.acceptNum}</span></td>
                                                        <td style={{ textAlign: 'center' }}><span style={{ display: 'inline-block', height: 15, lineHeight: '16px', width: 60, whiteSpace: 'nowrap' }}>
                                                            <div>
                                                                {
                                                                    itt.isLack === 1 ? <Badge status="error" text={<span style={{ color: 'red' }}>欠料</span>} /> : null
                                                                }
                                                                <div>
                                                                    {
                                                                        itt.outStatus === 1 ? <Badge status="error" text={<span style={{ color: 'red' }}>待确认</span>} /> : null
                                                                    }
                                                                </div>
                                                                <div>
                                                                    {
                                                                        itt.outStatus === 2 ? <Badge status="processing" text='未完成' /> : itt.outStatus === 3 ? <Badge status="success" text="已完成" /> : null
                                                                    }
                                                                </div>
                                                            </div>
                                                        </span></td>
                                                    </tr>
                                                </>
                                            })}
                                        </tbody>
                                    </table>
                                    <div className="printBreak" style={{ marginTop: '10' }}>
                                        <div style={{ width: '100%' }}>
                                            <div gutter={24} style={{ textAlign: 'left', display: 'flex' }}>
                                                <div style={{ flex: 4 }}></div>
                                                <div style={{ textAlign: 'center', flex: 16 }} >第{pa + 1}页,共{this.state.pages.length}页</div>
                                                <div style={{ flex: 4 }}></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        })
                    }
                </div>
            </div >
        )
    }
}
export default Form.create()(withRouter(StayGrant))